function prof_data = anneal(num_ep, alone, overlap);

% ANNEAL - anneals separate profiles & creates array for averaging
%
%    PROF = ANNEAL(EP, ALONE, OVERLAP) anneals two sets of profile data
%    to create one set of profile data for averaging.  EP contains the
%    number of episodes, ALONE contains the indices over which the two
%    profiles don't overlap, and OVERLAP contains the indices over which
%    they do overlap.

% By:   S.C. Molitor (smolitor@med.unc.edu)
% Date: May 9, 2000

% initialize output

prof_data = [];

% validate arguments

if (nargin ~= 3)
   msgbox('Invalid number of arguments', 'ANNEAL Error', 'warn');
   return
elseif (~isnumeric(num_ep) | ~all(size(num_ep) == [1 1]))
   msgbox('EP must be a scalar', 'ANNEAL Error', 'warn');
   return
elseif (~isnumeric(alone) | ~all(size(alone) == [2 2]))
   msgbox('ALONE must be a 2 x 2 array', 'ANNEAL Error', 'warn');
   return
elseif (~isnumeric(overlap) | ~all(size(overlap) == [2 2]))
   msgbox('OVERLAP must be a 2 x 2 array', 'ANNEAL Error', 'warn');
   return
elseif (diff(overlap(1, :)) ~= diff(overlap(2, :)))
   msgbox('OVERLAP index range must be same size', 'ANNEAL Error', 'warn');
   return
end

% make sure arrays exist
% make sure indices are appropriate for profiles

ep_data = [];
for i = 1 : num_ep
   ep_array = evalin('base', sprintf('ep%d', i));
   if (size(ep_array, 2) ~= 4)
      msgbox(sprintf('EP%d must exist & have 4 columns', i), 'ANNEAL Error', 'warn');
      return
   else
      ep_data = [ep_data ep_array];
   end
end

% create output array with appropriate size
% first column contains annealed distance
% use linear weighting

prof_data = zeros(diff(alone(1, :)) + diff(overlap(1, :)) + diff(alone(2, :)) + 3, num_ep + 1);
weight = [0 : diff(overlap(1, :))]'/diff(overlap(1, :));
prof_data(1 : diff(alone(1, :)) + 1, 1) = ep_data(alone(1, 1), 1) + ...
   cumsum([0; diff(ep_data(alone(1, 1) : alone(1, 2), 1))]);
prof_data(diff(alone(1, :)) + 2 : end - diff(alone(2, :)) - 1, 1) = ep_data(overlap(1, 1), 1) + ...
   (1 - weight).*cumsum([0; diff(ep_data(overlap(1, 1) : overlap(1, 2), 1))]) + ...
   weight.*cumsum([0; diff(ep_data(overlap(2, 1) : overlap(2, 2), 3))]);
prof_data(end - diff(alone(2, :)) : end, 1) = prof_data(end - diff(alone(2, :)) - 1, 1) + ...
   ep_data(alone(2, 1), 3) - ep_data(overlap(2, 2), 3) + cumsum([0; diff(ep_data(alone(2, 1) : alone(2, 2), 3))]);

% anneal profiles
% use linear weighting

for i = 1 : num_ep
   col1 = 4*(i - 1) + 2;
   col2 = 4*i;
   prof_data(1 : diff(alone(1, :)) + 1, i + 1) = ep_data(alone(1, 1) : alone(1, 2), col1);
   prof_data(diff(alone(1, :)) + 2 : end - diff(alone(2, :)) - 1, i + 1) = ...
      (1 - weight).*ep_data(overlap(1, 1) : overlap(1, 2), col1) + ...
      weight.*ep_data(overlap(2, 1) : overlap(2, 2), col2);
   prof_data(end - diff(alone(2, :)) : end, i + 1) = ep_data(alone(2, 1) : alone(2, 2), col2);
end
return
